package com.zys.el.search.service;

import com.zys.el.search.client.NoteClient;
import com.zys.el.search.client.UserClient;
import com.zys.el.search.dao.AnticleDao;
import com.zys.el.search.po.Anticle;
import com.zys.el.user.po.Note;
import com.zys.el.user.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AnticleService {


    @Autowired
    private NoteClient noteClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private AnticleDao anticleDao;

    public void buildAnticles() {
        List<Note> notes = noteClient.selectAll();
        List<Anticle> anticles = new ArrayList<>();
        for (Note note : notes) {
            User edit = userClient.edit(note.getAuthorId());
            anticles.add(Anticle.builder().noteId(note.getId())
                    .authorId(note.getAuthorId())
                    .content(note.getContentPath())
                    .introduction(note.getNoteItem())
                    .item(note.getItem())
                    .userImage(edit.getImage())
                    .userName(edit.getName())
                    .build());
        }
        try {
            anticleDao.addAllDoc(anticles);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加载单个note到es
     * @param note
     * @return
     */
    public boolean addAnticle(Note note) {
        Long authorId = note.getAuthorId();
        User edit = userClient.edit(authorId);
        Anticle build = Anticle.builder().noteId(note.getId())
                .authorId(note.getAuthorId())
                .content(note.getContentPath())
                .introduction(note.getNoteItem())
                .item(note.getItem())
                .userImage(edit.getImage())
                .userName(edit.getName())
                .build();
        boolean b = anticleDao.addDoc(build);
        return b;
    }

    /**
     * 根据id删除note
     * @param id
     * @return
     */
    public boolean deleteById(Long id) {
        Boolean aBoolean = anticleDao.deleteDocById(id);
        return aBoolean;
    }

}
